package rsj.service;

import com.rlyy.aibase.utils.base.MapNode;
import com.rlyy.aibase.utils.base.Node;
import com.rlyy.aibase.utils.base.TableNode;
import common.exec.RsjIllegalArgueException;
import common.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import rsj.dao.BaseDao;
import rsj.dao.OrgpDao;
import rsj.db.dbutils.UniqueID;
import rsj.sql.user.UserDao;
import rsj.table.SYS_ORGPTYPE;
import rsj.utils.RedisUtils;

import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.rlyy.aibase.utils.helpers.DateHelper.parseString;
@Component
public class OrgpService {

	private static OrgpDao infoDao = OrgpDao.getInstance();

	@Autowired
	private UserDao userDao;

	public void orgpInsert(Connection conn,MapNode data) throws SQLException{
		String id = String.valueOf(UniqueID.generateId());
		String prodName = data.getValue("Orgp_Prod_Name");
	   	String prodId = data.getValue("Orgp_Prod_Id");
	   	String ctime = data.getValue("Orgp_Ctime");
	   	String type = data.getValue("Orgp_Type");
	   	String billmethod = data.getValue("Orgp_Billmethod");
	   	String endtime = data.getValue("Orgp_Endtime");
	   	String operson = data.getValue("Orgp_Operson");
	   	String orgId = data.getValue("Org_Id");
	   	String contractime = data.getValue("Orgp_Contractime");
	   	String buyamount = data.getValue("Orgp_Buyamount");
	   	String prodUid = data.getValue("Orgp_Prod_Uid");

		Assert.isNotBlank(prodName,"产品名称不能为空");
		Assert.isNotBlank(prodId,"产品Id不能为空");
		Assert.isNotBlank(ctime,"生效时间不能为空");
		Assert.isNotBlank(contractime,"合同日期不能为空");
		Assert.isNotBlank(endtime,"到期时间不能为空");
		Assert.isNotBlank(operson,"操作人员不能为空");
		Assert.isNotBlank(orgId,"机构Id不能为空");
		Assert.isNotBlank(prodUid, "产品编号Orgp_Prod_Uid不能为空");

		// 按条情况下就是购买
		if(SYS_ORGPTYPE.Orgp_Single.equalsIgnoreCase(billmethod)){
			type = SYS_ORGPTYPE.Orgp_Type_Collect;// 账单类型 购买
			buyamount = "0";// 默认单条计费，购买量为0
		}
		// 包量 情况下才允许试用，试用量，购买量，试用，购买类型
		else if(SYS_ORGPTYPE.Orgp_Combina.equalsIgnoreCase(billmethod)){
			Assert.isNotBlank(type, "组合包量必须选择");
			Assert.isNotBlank(buyamount,"组合包量计费，购买数量不能为空（Orgp_Buyamount）");
		}
		// 按企业包量
		else if(SYS_ORGPTYPE.Orgp_Company.equalsIgnoreCase(billmethod)){
			Assert.isNotBlank(type, "企业包量必须选择");
			Assert.isNotBlank(buyamount,"企业包量计费，购买数量不能为空（Orgp_Buyamount）");
		}
		else {
			throw new RsjIllegalArgueException("不支持的计费类型！");
		}

    	Date cdate =  new Date( parseString(ctime,"yyyy-MM-dd").getTime());
    	Date edate =  new Date( parseString(endtime,"yyyy-MM-dd").getTime());
    	Date contracdate =  new Date( parseString(contractime,"yyyy-MM-dd").getTime());

    	checkIfExistSameOrgP(orgId, prodId, contracdate, conn);//orgp_org_id,orgp_prod_id,orgp_contractime

	   	infoDao.orgpInsert(conn, id, prodName, prodId, cdate, type, billmethod, edate, operson
				, orgId, contracdate,buyamount,prodUid);

	}

	private void checkIfExistSameOrgP(String orgId, String prodId, Date contractime, Connection conn) {
		Node node = infoDao.countByOrgProCon(orgId, prodId, contractime, conn);
		Assert.isTrue(node.valueInt() == 0, "同一合同生效日期对应同一机构和产品，只能存在一个！");
	}

//	public static void main(String[] args) {
//		BaseDao.invokeSql(conn -> {
//			new OrgpService().checkIfExistSameOrgP("1058835273914793984", "1060141433787793408",
//					new Date( parseString("2019-11-12","yyyy-MM-dd").getTime())
//					,conn);
//			return null;
//		});
//	}

	public MapNode rechargeList(Connection conn,MapNode data) throws SQLException{
		int size = data.getValueIntDef("Page_Size", 10);
		int pcount = data.getValueIntDef("Page_Count", 1);
		String ctime = data.getValue("Orgp_Ctime_Start");
		String etime = data.getValue("Orgp_Ctime_End");
		String orgId = data.getValue("Org_Id");

		String All_Status = data.getValue("All_Status");

		Assert.isNotBlank(orgId,"机构Id不能为空");

		if("1".equals(All_Status)){
			return infoDao.rechargeListAll(conn, ctime, etime, orgId, size, pcount);
		} else {
			return infoDao.rechargeList(conn, ctime, etime, orgId, size, pcount);
		}
	}

	public MapNode satisfyList(Connection conn,MapNode data,String userId) throws SQLException{
		int size = data.getValueIntDef("Page_Size", 10);
		int pcount = data.getValueIntDef("Page_Count", 1);
		String orgId = this.getOrgId(userId);
		String querykey = data.getValue("Query_Key");
		Assert.isNotBlank(orgId,"机构Id不能为空");

		return infoDao.satisfyList(conn, orgId,querykey, size, pcount);
	}

	public MapNode probationList(Connection conn,MapNode data,String userId) throws SQLException{
		int size = data.getValueIntDef("Page_Size", 10);
		int pcount = data.getValueIntDef("Page_Count", 1);
		String orgId = this.getOrgId(userId);
		Assert.isNotBlank(orgId,"机构Id不能为空");
		String querykey = data.getValue("Query_Key");

		return infoDao.probationList(conn, orgId,querykey, size, pcount);
	}

	public MapNode collectionList(Connection conn,MapNode data,String userId) throws SQLException{
		int size = data.getValueIntDef("Page_Size", 10);
		int pcount = data.getValueIntDef("Page_Count", 1);
		String orgId = this.getOrgId(userId);
		String querykey = data.getValue("Query_Key");
		Assert.isNotBlank(orgId,"机构Id不能为空");

		return infoDao.collectionList(conn, orgId, querykey, size, pcount);
	}


	public String getOrgId(String userId){
		MapNode mapNode = userDao.queryOrgIdByUser(userId);
		String orgId = mapNode.getValue("User_Org_Id");
		Assert.isNotBlank(orgId,"机构Id不能为空");
		return orgId;
	}

	public void updateStartStop(Connection conn,MapNode data) throws SQLException{
		String orgpId = data.getValue("Orgp_Id");
		String status = data.getValue("Orgp_Orgpstatus");

		Assert.isNotBlank(orgpId,"合同Id不能为空");
		Assert.isNotBlank(status,"状态不能为空");

		infoDao.updateStartStop(conn, orgpId, status);
	}

	public static void main(String[] args) {
		new BaseDao().invokeSql(conn -> {

			try {
				new OrgpService().updateForTimmer(conn);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			return null;
		});
	}

	public void updateForTimmer(Connection conn)throws SQLException{

		infoDao.updateOrgpStatus(conn);
		infoDao.updateProdStatus(conn);

		TableNode tn = infoDao.findSysStatus(conn);
		List<Map<String,Object>> list = tn.toList();
		for(Map<String,Object> map : list){
			String key = "rsj|prodStatus|"+map.get("Aut_Keyid")+"_"+map.get("Prod_Uid");

			HashMap<String,String> redisMap = new HashMap<>();
			redisMap.put("Sta_Orgp_Id", (String) map.get("Sta_Orgp_Id"));
			redisMap.put("Sta_Status", (String) map.get("Sta_Status"));
			RedisUtils.hmset(key,redisMap,3*60);
//			JedisUtil.hMSet(key, JSON.toJSONString(redisMap), ThreeMinutes, TidHelper.tid());
		}

	}


}
